// 音效管理服务
import { ref } from 'vue';

class AudioService {
  constructor() {
    // 音效状态
    this.soundEnabled = ref(true);
    this.volume = ref(0.7);
    
    // 音效缓存
    this.sounds = {};
    this.playingInstances = new Map(); // 跟踪正在播放的音频实例
    this.isInitialized = false;
    
    // 预定义音效列表
    this.soundEffects = {
      attack: '/sounds/attack.mp3',
      skill: '/sounds/skill.mp3',
      damage: '/sounds/damage.mp3',
      victory: '/sounds/victory.mp3',
      defeat: '/sounds/defeat.mp3',
      select: '/sounds/select.mp3',
      background: '/sounds/background.mp3'
    };
    
    // 背景音乐对象
    this.backgroundMusic = null;
    
    // 音频上下文
    this.audioContext = null;
  }
  
  // 初始化音效服务
  async init() {
    if (this.isInitialized) return;
    
    try {
      // 检查浏览器是否支持音频
      if (!window.Audio) {
        console.warn('当前浏览器不支持音频功能');
        return;
      }
      
      // 创建背景音乐
      this.backgroundMusic = new Audio(this.soundEffects.background);
      this.backgroundMusic.loop = true;
      this.backgroundMusic.volume = this.volume.value * 0.3;
      
      // 使用Web Audio API进行更高效的音频管理
      try {
        const AudioContext = window.AudioContext || window.webkitAudioContext;
        this.audioContext = new AudioContext();
      } catch (e) {
        console.warn('Web Audio API不受支持，使用基本的Audio元素');
      }
      
      // 预加载所有音效
      await this.preloadSounds();
      this.isInitialized = true;
    } catch (error) {
      console.error('音效服务初始化失败:', error);
    }
  }
  
  // 预加载音效
  async preloadSounds() {
    try {
      console.log('预加载音效...');
      const preloadPromises = [];
      
      for (const [key, path] of Object.entries(this.soundEffects)) {
        if (key !== 'background') {
          try {
            const sound = new Audio(path);
            sound.volume = this.volume.value;
            this.sounds[key] = sound;
            
            // 添加预加载Promise
            preloadPromises.push(
              sound.load().catch(err => {
                console.warn(`音效 ${key} 预加载失败，将在需要时加载: ${err.message}`);
              })
            );
          } catch (error) {
            console.warn(`无法创建音效元素 ${key}: ${error.message}`);
          }
        }
      }
      
      // 等待所有预加载完成
      await Promise.all(preloadPromises);
    } catch (error) {
      console.error('音效加载失败:', error);
    }
  }
  
  // 播放音效
  playSound(soundName) {
    if (!this.soundEnabled.value || !this.sounds[soundName]) return;
    
    try {
      // 为避免重叠播放，创建音频副本
      const soundClone = this.sounds[soundName].cloneNode();
      soundClone.volume = this.volume.value;
      
      // 跟踪播放实例
      const instanceId = `${soundName}_${Date.now()}`;
      this.playingInstances.set(instanceId, soundClone);
      
      // 播放完成后清理
      soundClone.addEventListener('ended', () => {
        this.playingInstances.delete(instanceId);
      });
      
      soundClone.addEventListener('error', (error) => {
        console.warn(`播放音效 ${soundName} 时出错:`, error);
        this.playingInstances.delete(instanceId);
      });
      
      soundClone.play();
      
      // 记录音效播放，用于调试
      return { success: true };
    } catch (error) {
      console.error(`播放音效失败: ${soundName}`, error);
      return { success: false, error };
    }
  }
  
  // 播放背景音乐
  playBackgroundMusic() {
    if (!this.soundEnabled.value || !this.backgroundMusic) return;
    
    try {
      console.log('播放背景音乐');
      
      // 检查是否已经在播放
      if (this.backgroundMusic.paused) {
        // 恢复或重新开始播放
        if (this.backgroundMusic.currentTime === this.backgroundMusic.duration) {
          this.backgroundMusic.currentTime = 0;
        }
        this.backgroundMusic.play().catch(error => {
          console.warn('无法播放背景音乐:', error.message);
        });
      }
    } catch (error) {
      console.error('播放背景音乐失败:', error);
    }
  }
  
  // 停止背景音乐
  stopBackgroundMusic() {
    try {
      console.log('停止背景音乐');
      if (this.backgroundMusic) {
        this.backgroundMusic.pause();
        this.backgroundMusic.currentTime = 0;
      }
    } catch (error) {
      console.error('停止背景音乐失败:', error);
    }
  }
  
  // 暂停背景音乐
  pauseBackgroundMusic() {
    if (this.backgroundMusic && !this.backgroundMusic.paused) {
      this.backgroundMusic.pause();
    }
  }
  
  // 切换音效开关
  toggleSound() {
    this.soundEnabled.value = !this.soundEnabled.value;
    
    if (!this.soundEnabled.value) {
      this.stopBackgroundMusic();
    } else {
      this.playBackgroundMusic();
    }
    
    return this.soundEnabled.value;
  }
  
  // 设置音量
  setVolume(newVolume) {
    this.volume.value = Math.max(0, Math.min(1, newVolume));
    
    // 更新背景音乐音量
    if (this.backgroundMusic) {
      this.backgroundMusic.volume = this.volume.value * 0.3;
    }
    
    // 更新所有音效的音量
    for (const sound of Object.values(this.sounds)) {
      sound.volume = this.volume.value;
    }
    
    // 更新所有正在播放的实例音量
    for (const sound of this.playingInstances.values()) {
      sound.volume = this.volume.value;
    }
  }
  
  // 获取音效开关状态
  getSoundEnabled() {
    return this.soundEnabled.value;
  }
  
  // 获取音量
  getVolume() {
    return this.volume.value;
  }
  
  // 清理所有正在播放的音效
  clearAllSounds() {
    // 停止所有正在播放的实例
    for (const [id, sound] of this.playingInstances.entries()) {
      try {
        sound.pause();
      } catch (e) {
        // 忽略错误
      }
      this.playingInstances.delete(id);
    }
  }
  
  // 释放资源
  destroy() {
    this.clearAllSounds();
    this.stopBackgroundMusic();
    
    // 清理资源引用
    this.backgroundMusic = null;
    this.sounds = {};
    this.playingInstances.clear();
    
    // 关闭音频上下文
    if (this.audioContext) {
      try {
        this.audioContext.close();
      } catch (e) {
        // 忽略错误
      }
      this.audioContext = null;
    }
    
    this.isInitialized = false;
  }
}

// 导出单例实例
export default new AudioService();
